"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClubDao = void 0;
const UserDao_1 = require("../../account_server/dao/UserDao");
const LogServerHelper_1 = require("../../log_server/LogServerHelper");
const ErrorCode_1 = require("../../src/config/ErrorCode");
const DaoBase_1 = require("../../src/engine/dao/DaoBase");
const DateUtil_1 = require("../../src/engine/utils/DateUtil");
const DBSourceManager_1 = require("../../src/engine/utils/DBSourceManager");
const Logger_1 = require("../../src/engine/utils/Logger");
const MysqlManager_1 = require("../../src/engine/utils/MysqlManager");
const RandomUtil_1 = require("../../src/engine/utils/RandomUtil");
const ResponseModel_1 = require("../../src/model/ResponseModel");
const ClubConfig_1 = require("../config/ClubConfig");
const ClubEntity_1 = require("../entity/ClubEntity");
const ClubUserEntity_1 = require("../entity/ClubUserEntity");
const ClubModel_1 = require("../model/ClubModel");
const ClubUserDao_1 = require("./ClubUserDao");
class ClubDao extends DaoBase_1.DaoBase {
    static getRepository() {
        return __awaiter(this, void 0, void 0, function* () {
            let repository = yield this.getRepositoryBase(ClubEntity_1.ClubEntity, this.getGameDbName());
            return repository;
        });
    }
    static randomClubId(randomCount = 0) {
        return __awaiter(this, void 0, void 0, function* () {
            let clubid = RandomUtil_1.default.nextInt(100000, 999999);
            let isExist = yield this.is_club_exist(clubid);
            if (!isExist) {
                return clubid;
            }
            else {
                // Logger.log("randomClubId==", randomCount)
                randomCount++;
                if (randomCount > 5) {
                    Logger_1.Logger.error("randomClubId 俱乐部id重复", clubid);
                    return 0;
                }
                else {
                    return this.randomClubId(randomCount);
                }
            }
        });
    }
    static is_club_exist(clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let repository = yield this.getRepository();
            let result = yield repository.findOneBy({
                clubid: clubid
            });
            return result;
        });
    }
    static create_club(clubEntity) {
        return __awaiter(this, void 0, void 0, function* () {
            let repository = yield this.getRepository();
            let result = yield DBSourceManager_1.DBSourceManager.instance.insert(repository, clubEntity);
            if (result && result.raw["affectedRows"] > 0) {
                let isSuc = yield ClubUserDao_1.ClubUserDao.add_club_user(clubEntity.clubid, clubEntity.creator, ClubConfig_1.ClubConfig.Club_Actor_Type.owner, ClubConfig_1.ClubConfig.Club_merber_state_type.nomal);
                if (isSuc) {
                    return true;
                }
                else {
                    return false;
                }
            }
            return false;
        });
    }
    static get_club_simple(userid, clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = `select * from t_clubusers,t_clublist,t_users where t_clubusers.userid = ? and  t_clublist.clubid=? and t_clubusers.clubid = t_clublist.clubid  and  t_clubusers.userid = t_users.userid and t_clubusers.user_state=?`;
            let repository = yield this.getRepository();
            let sqlParams = [userid, clubid, ClubConfig_1.ClubConfig.Club_merber_state_type.nomal];
            let results = yield repository.query(sql, sqlParams);
            Logger_1.Logger.log("get_club_simple===", sql, sqlParams);
            Logger_1.Logger.log("get_club_simple=2==", results);
            if (!results || !results.length) {
                return null;
            }
            let club = ClubModel_1.ClubModel.data2IClubInfo(results[0]);
            return club;
        });
    }
    static get_club_list(userid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = `select * from t_clubusers,t_clublist,t_users where t_clubusers.userid = ? and t_clubusers.clubid = t_clublist.clubid  and  t_clubusers.userid = t_users.userid and t_clubusers.user_state=?`;
            let repository = yield this.getRepository();
            let sqlParams = [userid, ClubConfig_1.ClubConfig.Club_merber_state_type.nomal];
            let results = yield repository.query(sql, sqlParams);
            Logger_1.Logger.log("get_club_list=", results);
            if (!results || !results.length) {
                return [];
            }
            let clubs = results;
            for (let i = 0; i < clubs.length; i++) {
                let clubid = clubs[i]["clubid"];
                // 玩家数
                clubs[i]["usercount"] = yield ClubUserDao_1.ClubUserDao.getUserCountByClub(clubid);
            }
            Logger_1.Logger.log("get_club_list=", clubs);
            let resultClubs = ClubModel_1.ClubModel.data2IClubInfoList(clubs);
            return resultClubs;
        });
    }
    static join_club(userid, clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let respModel = new ResponseModel_1.ResponseModel();
            let clubEntity = yield this.is_club_exist(clubid);
            if (!clubEntity) {
                respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                respModel.msg = "俱乐部不存在!";
            }
            else {
                let clubUserEntity = yield ClubUserDao_1.ClubUserDao.get_club_user(clubid, userid);
                let canApply = true;
                let hadApply = false;
                if (clubUserEntity) {
                    let user_state = clubUserEntity.user_state;
                    if (user_state == ClubConfig_1.ClubConfig.Club_merber_state_type.apply) { // 已申请，等待
                        respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                        respModel.msg = "您已经提交过申请，请不要重复提交，等待管理员审核";
                        canApply = false;
                    }
                    else if (user_state == ClubConfig_1.ClubConfig.Club_merber_state_type.nomal) { // 已经是
                        respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                        respModel.msg = "您已经是此亲友圈成员，无需再次申请";
                        canApply = false;
                    }
                    else if (user_state == ClubConfig_1.ClubConfig.Club_merber_state_type.refuse) { // 被拒绝
                        hadApply = true;
                        clubUserEntity.user_state = ClubConfig_1.ClubConfig.Club_merber_state_type.apply;
                    }
                    else if (user_state == ClubConfig_1.ClubConfig.Club_merber_state_type.blacklist) { // 黑名单
                        respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                        respModel.msg = "您已经被此亲友圈拉入黑名单，无法申请";
                        canApply = false;
                    }
                    else {
                        Logger_1.Logger.warn("未识别加入亲友圈状态:", user_state);
                        respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                        respModel.msg = "您已经被此亲友圈拉入黑名单，无法申请";
                        canApply = false;
                    }
                }
                else {
                    clubUserEntity = new ClubUserEntity_1.ClubUserEntity();
                    clubUserEntity.id = null;
                    clubUserEntity.clubid = clubid;
                    clubUserEntity.userid = userid;
                    clubUserEntity.user_state = ClubConfig_1.ClubConfig.Club_merber_state_type.apply;
                    clubUserEntity.actor = ClubConfig_1.ClubConfig.Club_Actor_Type.general;
                    clubUserEntity.join_time = DateUtil_1.default.formatDateStr(DateUtil_1.default.now());
                }
                if (canApply) {
                    clubUserEntity = yield ClubUserDao_1.ClubUserDao.update_user(clubUserEntity);
                }
            }
            return respModel;
        });
    }
    static req_club_apply_list(clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = `select userid,nick_name,headimg, clubid,user_state,invite,lv from v_club_users where clubid = ? and user_state=0`;
            let sqlParams = [clubid];
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let rows = yield client.queryPromise(sql, sqlParams);
            let respModel = new ResponseModel_1.ResponseModel();
            if (rows) { //已经存在俱乐部数据
                respModel.code = ErrorCode_1.ErrorCode.Code.Suc;
                respModel.data = rows;
            }
            else {
                respModel.code = ErrorCode_1.ErrorCode.Code.Db_Error;
                respModel.msg = "查询俱乐部申请列表失败";
            }
            return respModel;
        });
    }
    static agreeApply(handle_userid, apply_userid, clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = "update t_clubusers set `state`=1, `approver`=?  where `userid`=? and clubid=?";
            let sqlParams = [handle_userid, apply_userid, clubid];
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                LogServerHelper_1.LogServerHelper.log_club_in_out_history(clubid, apply_userid, ClubConfig_1.ClubConfig.in_out_type.be_in, handle_userid);
                return true;
            }
            return false;
        });
    }
    static disagreeApply(handle_userid, apply_userid, clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = "update t_clubusers set `state`=3, `approver`=?   where `userid`=? and clubid=?";
            let sqlParams = [handle_userid, apply_userid, clubid];
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                return true;
            }
            return false;
        });
    }
    static get_v_club_user_view(clubid, userid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = `select * from v_club_users where clubid = ? and userid=?`;
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sqlParams = [clubid, userid];
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows.length) { //已经存在俱乐部数据
                return rows[0];
            }
        });
    }
    static get_v_club_user_list_by_page(clubid, page_size, cur_page) {
        return __awaiter(this, void 0, void 0, function* () {
            let startIndex = (cur_page - 1) * page_size;
            let sql = "select * from v_club_users where clubid=? and (user_state=1 or user_state=2)  order by actor desc limit ?,?";
            let sqlParams = [clubid, startIndex, page_size];
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let rows = yield client.queryPromise(sql, sqlParams);
            Logger_1.Logger.log("get_v_club_user_list_by_page==", sql, sqlParams, rows);
            if (rows && rows.length > 0) {
                return rows;
            }
            return [];
        });
    }
    static getClubMerberTotalNum(clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = "select count(*) from t_clubusers where clubid=?";
            let sqlParams = [clubid];
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let rows = yield client.queryPromise(sql, sqlParams);
            Logger_1.Logger.log("getClubMerberTotalNum==", clubid, rows);
            if (rows) {
                return rows[0]["count(*)"];
            }
            return 0;
        });
    }
    static delete_club_user(clubid, userid) {
        return __awaiter(this, void 0, void 0, function* () {
            let sql = "delete from t_clubusers  where `userid`=? and clubid=?";
            let sqlParams = [userid, clubid];
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                LogServerHelper_1.LogServerHelper.log_club_in_out_history(clubid, userid, ClubConfig_1.ClubConfig.in_out_type.my_out, 0);
                return true;
            }
            return false;
        });
    }
    static delete_clut_users(clubid, useridList) {
        return __awaiter(this, void 0, void 0, function* () {
            if (useridList.length > 0) {
                let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
                let sql = "delete from t_clubusers  where clubid=? and actor != " + ClubConfig_1.ClubConfig.Club_Actor_Type.owner + "  and ( `userid`=" + useridList[0];
                for (let i = 1; i < useridList.length; i++) {
                    sql += " or `userid`=" + useridList[i];
                }
                sql += " )";
                let sqlParams = [clubid];
                let results = yield client.queryPromise(sql, sqlParams);
                Logger_1.Logger.log("delete_clut_users======", sql, results);
                if (results && results["affectedRows"] > 0) {
                    return true;
                }
            }
            return false;
        });
    }
    static add_club_table_group(clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "insert into t_club_table_group (clubid) values(?);";
            let sqlParams = [clubid];
            let results = yield client.queryPromise(sql, sqlParams);
            if (results && results["affectedRows"] > 0) {
                return true;
            }
            else {
                return false;
            }
        });
    }
    static delete_club_table_group(id) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "delete from t_club_table_group where id=?";
            let sqlParams = [id];
            let results = yield client.queryPromise(sql, sqlParams);
            if (results && results["affectedRows"] > 0) {
                return true;
            }
            else {
                return false;
            }
        });
    }
    static get_club_table_group_no_userinfo(clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "select * from t_club_table_group where clubid=?";
            let sqlParams = [clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            let resultList = [];
            if (rows && rows.length > 0) {
                for (let i = 0; i < rows.length; i++) {
                    let resultObj = {
                        "id": rows[i]["id"],
                        "clubid": rows[i]["clubid"],
                    };
                    let users = rows[i]["users"];
                    if (users) {
                        let userArr = users.split(",");
                        let userids = [];
                        for (let j = 0; j < userArr.length; j++) {
                            let userid = parseInt(userArr[j]);
                            userids.push(userid);
                        }
                        resultObj["userids"] = userids;
                    }
                    resultList[i] = resultObj;
                }
            }
            return resultList;
        });
    }
    static get_club_table_group(clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "select * from t_club_table_group where clubid=?";
            let sqlParams = [clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows.length > 0) {
                let alluseridList = [];
                let resultList = [];
                for (let i = 0; i < rows.length; i++) {
                    let resultObj = {
                        "id": rows[i]["id"],
                        "clubid": rows[i]["clubid"],
                    };
                    let users = rows[i]["users"];
                    if (users) {
                        let userArr = users.split(",");
                        let userids = [];
                        for (let j = 0; j < userArr.length; j++) {
                            let userid = parseInt(userArr[j]);
                            userids.push(userid);
                            if (!alluseridList.includes(userid)) {
                                alluseridList.push(userid);
                            }
                        }
                        resultObj["userids"] = userids;
                    }
                    resultList[i] = resultObj;
                }
                let userInfoList = yield UserDao_1.UserDao.get_userlistinfo(alluseridList);
                for (let i = 0; i < resultList.length; i++) {
                    let resultObj = resultList[i];
                    let resultUsers = [];
                    let userids = resultObj["userids"];
                    if (userids && userids.length > 0) {
                        for (let j = 0; j < userInfoList.length; j++) {
                            let userid = userInfoList[j].userid;
                            if (userids.includes(userid)) {
                                resultUsers.push(userInfoList[j]);
                            }
                        }
                    }
                    resultObj["resultUsers"] = resultUsers;
                }
                return resultList;
            }
            else {
                return null;
            }
        });
    }
    static add_user_to_club_group(id, userid) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "select * from t_club_table_group where id=?";
            let sqlParams = [id];
            let rows = yield client.queryPromise(sql, sqlParams);
            let respModel = new ResponseModel_1.ResponseModel();
            if (rows && rows.length) {
                let users = rows[0]["users"];
                if (users) {
                    let userArr = users.split(",");
                    if (userArr.includes(userid + "")) {
                        respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                        respModel.msg = "该用户已经在分组里面了";
                    }
                    else {
                        userArr.push(userid + "");
                        users = userArr.toString();
                        respModel.code = ErrorCode_1.ErrorCode.Code.Suc;
                    }
                }
                else {
                    users = userid + "";
                    respModel.code = ErrorCode_1.ErrorCode.Code.Suc;
                }
                if (respModel.code == ErrorCode_1.ErrorCode.Code.Suc) {
                    sql = "update t_club_table_group set `users`=? where `id`=?";
                    sqlParams = [users, id];
                    rows = yield client.queryPromise(sql, sqlParams);
                    if (rows && rows["affectedRows"] > 0) {
                    }
                    else {
                        respModel.code = ErrorCode_1.ErrorCode.Code.Db_Error;
                        respModel.msg = "数据库更新分组失败";
                    }
                }
            }
            else {
                respModel.code = ErrorCode_1.ErrorCode.Code.Db_Error;
                respModel.msg = "数据库查询不到该分组id";
            }
            return respModel;
        });
    }
    static del_user_to_club_group(id, userid) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "select * from t_club_table_group where id=?";
            let sqlParams = [id];
            let rows = yield client.queryPromise(sql, sqlParams);
            let respModel = new ResponseModel_1.ResponseModel();
            if (rows && rows.length) {
                let users = rows[0]["users"];
                if (users) {
                    let userArr = users.split(",");
                    let index = userArr.indexOf(userid + "");
                    userArr.splice(index, 1);
                    users = userArr.toString();
                    sql = "update t_club_table_group set `users`=? where `id`=?";
                    sqlParams = [users, id];
                    rows = yield client.queryPromise(sql, sqlParams);
                    if (rows && rows["affectedRows"] > 0) {
                    }
                    else {
                        respModel.code = ErrorCode_1.ErrorCode.Code.Db_Error;
                        respModel.msg = "数据库更新分组失败";
                    }
                }
                else {
                    respModel.code = ErrorCode_1.ErrorCode.Code.Db_Error;
                    respModel.msg = "数据库查询不到该分组用户";
                }
            }
            else {
                respModel.code = ErrorCode_1.ErrorCode.Code.Db_Error;
                respModel.msg = "数据库查询不到该分组id";
            }
            return respModel;
        });
    }
    static update_club_setting(clubid, seemember, seerank, limit_join) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "update t_clublist set `seemember`=?,`seerank`=?,`limit_join`=?  where clubid=?";
            let sqlParams = [seemember, seerank, limit_join, clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                return true;
            }
            return false;
        });
    }
    static update_club_state(clubid, state) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "update t_clublist set `state`=?  where clubid=?";
            let sqlParams = [state, clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            Logger_1.Logger.log("update_club_state===", sql, sqlParams, rows);
            if (rows && rows["affectedRows"] > 0) {
                return true;
            }
            return false;
        });
    }
    static delete_club(clubid) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "delete from  t_clublist where clubid=?";
            let sqlParams = [clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                sql = "delete from t_clubusers where clubid=?";
                rows = yield client.queryPromise(sql, sqlParams);
                sql = "delete from t_club_table_group where clubid=?";
                rows = yield client.queryPromise(sql, sqlParams);
                return true;
            }
            return false;
        });
    }
    static club_fix_notice(clubid, message) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "update t_clublist set `message`=?  where clubid=?";
            let sqlParams = [message, clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                return true;
            }
        });
    }
    static set_club_administrator(clubid, userid, actor, quanxian) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "update t_clubusers set `actor`=?,`quanxian`=? where `userid`=? and `clubid`=? ";
            let sqlParams = [actor, quanxian, userid, clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                return true;
            }
            return false;
        });
    }
    static set_club_member_quanxian(clubid, userid, quanxian) {
        return __awaiter(this, void 0, void 0, function* () {
            let client = yield MysqlManager_1.MysqlManager.instance.getDb(this.getGameDbName());
            let sql = "update t_clubusers set `quanxian`=? where `userid`=? and `clubid`=? ";
            let sqlParams = [quanxian, userid, clubid];
            let rows = yield client.queryPromise(sql, sqlParams);
            if (rows && rows["affectedRows"] > 0) {
                return true;
            }
            return false;
        });
    }
}
exports.ClubDao = ClubDao;
